package com.lkm.app_ui.ui.sale;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;

import com.lkm.app_ui.MBaseFragment;
import com.lkm.app_ui.R;
import com.lkm.app_ui.RouterUINavigation;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.help.AppUIHelp;
import com.lkm.app_ui.help.HandleDialog;
import com.lkm.app_ui.help.LockKeyManager;
import com.lkm.app_ui.help.RootCommand;
import com.lkm.app_ui.jz.bean.GetPayBean;
import com.lkm.app_ui.jz.net.PayApi;
import com.lkm.app_ui.jz.ui.fragment.ShopScreenFragment;
import com.lkm.app_ui.jz.util.JzUtil;
import com.lkm.app_ui.jz.util.Print;
import com.lkm.app_ui.m.fun.DelegatePayTask;
import com.lkm.app_ui.m.fun.OnKeyNumberEvent;
import com.lkm.app_ui.ui.fj.FjApp;
import com.lkm.app_ui.ui.fj.FjSaleFragment;
import com.lkm.app_ui.ui.fj.OnFjInfoEvent;
import com.lkm.app_ui.ui.sale.p.GoodsSelectFragment;
import com.lkm.app_ui.ui.sale.p.Pfactory;
import com.lkm.comlib.help.ImageViewLoadHelp;
import com.lkm.comlib.help.ViewHelp;
import com.lkm.comlib.help.ViewUIHelp;
import com.lkm.comlib.ui.BaseFragmentActivity;
import com.lkm.comlib.ui.BaseHoldAdapter;
import com.lkm.comlib.ui.IHoldView;
import com.lkm.frame.P;
import com.lkm.frame.otto.LinkBusCycleWrapper;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.util.CycleHelp;
import com.lkm.javatool.CollectionHelp;
import com.lkm.javatool.NumberHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.market2_0.entity.BasisEntity;
import com.lkm.market2_0.entity.FairTo;
import com.lkm.market2_0.entity.PayTo;
import com.lkm.market2_0.help.SteelardHelp;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;
import com.lkm.market2_0.m.steelyardserver.OnSteelyardKeyEvent;
import com.lkm.mvp.BinPresenter2View;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


public class SaleUIFragment extends MBaseFragment {


    public static SaleUIFragment getInstance(boolean isInnerView) {
        SaleUIFragment f    = new SaleUIFragment();
        Bundle         data = new Bundle();
        data.putBoolean("isInnerView", isInnerView);
        f.setArguments(data);
        return f;
    }


    private        Handler mainHandler;
    private static int     requestCode_FUN = 1;

    private SaleContract.Presenter         salePresenter;
    private SaleContract.SubtotalPresenter subtotalPresenter;
    private SaleContract.SubtotalViewEvent subtotalViewEvent;
    private boolean                        isEditSubtotal = false;
    private QrUIView                       qrUIView;
    private Boolean                        isSubPriceZero = false;

    @Override
    protected boolean configIsLockKey() {

        if (isEditSubtotal) return true;
        return false;
    }

    @Override
    protected int configLayoutResID() {

        FairTo fair = RunTimeData.steelyardInfo == null ? null : RunTimeData.steelyardInfo.getFair();

        if (fair != null && !StringHelp.isEmpty(fair.url)) {
            return R.layout.fragment_sale1;
        }


        PayTo payTo = RunTimeData.steelyardInfo == null ? null : RunTimeData.steelyardInfo.getPayInfo();
        if (payTo != null && payTo.isShowOutLinePayQr()) {
            return R.layout.fragment_sale1;
        }

        return R.layout.fragment_sale;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        qrUIView = new QrUIView();
    }

    @Override
    public void onDestroy() {
        //if (mWakelock != null) mWakelock.release();
        if (mLeftTime2ShopScreenDisposable != null) mLeftTime2ShopScreenDisposable.dispose();
        super.onDestroy();
        qrUIView.destroy();
    }

    TextView tv_wait_order;
    //    MyService myService = null;
    private PowerManager mPowerManager = null;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPowerManager = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
        boolean isInnerView = getArguments().getBoolean("isInnerView", false);
        if (isInnerView) {
            findViewById(R.id.vg_title).setVisibility(View.GONE);
//            view.setBackgroundResource(R.drawable.bg_corners_fff_60);
        }
//        try {
//            myService = new MyService(getContext());
//        } catch (Exception exception) {
//            myService = null;
//        }
        tv_wait_order = findViewById(R.id.tv_wait_order);


        qrUIView.showQr(configLayoutResID(), (ViewGroup) view);

        mainHandler = new Handler();

        salePresenter = Pfactory.getPresenter(holdCycleHelp());


        new SaleBaseView(salePresenter, getLifecycle());

        new SubtotalView(subtotalPresenter = Pfactory.getSubtotalPresenter(salePresenter, this));
        subtotalViewEvent = subtotalPresenter;
        new GoodImageView(Pfactory.getGoodImagePresenter(salePresenter, this));

        SaleContract.presenter = salePresenter;
        SaleContract.subtotalPresenter = subtotalPresenter;

        if (RunTimeData.isShowGoodsSelect) {
            View view1 = findViewById(R.id.fragment_goods_select);
            if (view1 != null) view1.setVisibility(View.VISIBLE);
            Fragment f = getChildFragmentManager().findFragmentById(R.id.fragment_goods_select);
            if (f == null)
                getChildFragmentManager().beginTransaction().replace(R.id.fragment_goods_select, GoodsSelectFragment.getInstance()).commit();
        } else {
            ViewHelp.removeParentView(findViewById(R.id.fragment_goods_select));
        }

        reOnKeyNumberEvent();

        reOnSteelyardKeyEvent();

        binfjInfo();

        pollingLeftTime2ShopScreen();
//        initWakeUpScreen();
    }

//    private PowerManager          pm;// init powerManager
//    private PowerManager.WakeLock mWakelock;
//
//    @SuppressLint("InvalidWakeLockTag")
//    private void initWakeUpScreen() {
//        P.d("Bill-> mWakelock->SDK_INT:" + Build.VERSION.SDK_INT);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            Context context = getContext();
//            if (context != null) {
//                pm = (PowerManager) context.getSystemService(POWER_SERVICE);
//            }
//            mWakelock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
//                    PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK |
//                    PowerManager.ON_AFTER_RELEASE, "target");
//            P.d("Bill-> mWakelock:" + mWakelock);
//        }
//
//
//    }


    private void binfjInfo() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnFjInfoEvent>() {

            @Override
            public void onReceiver(OnFjInfoEvent data) {
                if (FjApp.install.isEnable()) {
                    tv_wait_order.setVisibility(View.VISIBLE);
                    tv_wait_order.setText(Html.fromHtml(
                            "挂起订单数：<font color='red' size='30px'><big>" + FjApp.install.getFjWaitOrder().getSize() + "</big></font>单" +
                                    "   ；   总订单：<font color='red' size='30px'><big>" + FjApp.install.getFjInfo().orderCount + "</big></font>单")
                    );
                } else {
                    tv_wait_order.setVisibility(View.GONE);
                }
                if (FjApp.install.isEnable() && FjApp.install.getFjInfo().getCurFjOrder() != null) {

                    View view1 = findViewById(R.id.fj_sale);
                    if (view1 != null) view1.setVisibility(View.VISIBLE);
                    Fragment f = getChildFragmentManager().findFragmentById(R.id.fj_sale);
                    if (f == null)
                        getChildFragmentManager().beginTransaction().replace(R.id.fj_sale, new FjSaleFragment()).addToBackStack("fj_sale").commit();
                } else {
                    getChildFragmentManager().popBackStack("fj_sale", FragmentManager.POP_BACK_STACK_INCLUSIVE);
                }
            }

            @Override
            public Class<OnFjInfoEvent> getBusEventClass() {
                return OnFjInfoEvent.class;
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (SaleContract.presenter == salePresenter) {
            SaleContract.presenter = null;
        }
        if (SaleContract.subtotalPresenter == subtotalPresenter) {
            SaleContract.subtotalPresenter = null;
        }
    }


    private void reOnKeyNumberEvent() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnKeyNumberEvent>() {
            @Override
            public Class<OnKeyNumberEvent> getBusEventClass() {
                return OnKeyNumberEvent.class;
            }

            @Override
            public void onReceiver(OnKeyNumberEvent data) {
//                if (mWakelock != null) {
//                    P.d("Bill-> mWakelock:尝试唤醒");
//                    mWakelock.acquire();
//                }
//                if (myService != null) {
//                    P.d("Bill->打开屏幕：getBrightness:" + myService.getBrightness());
//                    myService.setBrightness(255);
//                }
                closeShopScreen();
                if (subtotalViewEvent != null) {
                    subtotalViewEvent.onKeyNumberEvent(data);
                }
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }


    private void reOnSteelyardKeyEvent() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnSteelyardKeyEvent>() {
            @Override
            public Class<OnSteelyardKeyEvent> getBusEventClass() {
                return OnSteelyardKeyEvent.class;
            }

            @Override
            public void onReceiver(OnSteelyardKeyEvent data) {
                closeShopScreen();
                if (data.isIntercepted()) return;

                if (subtotalViewEvent != null)
                    subtotalViewEvent.onSteelyardKeyEvent(data);

                if (data.isIntercepted()) return;
                if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_FUN) {
//                    RouterUINavigation.getInstance().showFjOrder((BaseFragmentActivity) getActivity());

                    RouterUINavigation.getInstance().showSaleFun((BaseFragmentActivity) getActivity(), SaleUIFragment.this, requestCode_FUN);
                    data.setIntercepted(true);
                }

            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }


    private class SaleBaseView extends BinPresenter2View<SaleContract.Presenter> implements SaleContract.View {
        private TextView tv_name1, tv_weight1, tv_price1, tv_money, tv_title, tv_weight_unit, tv_price_weight_unit;

        public SaleBaseView(SaleContract.Presenter basePresenter, Lifecycle lifecycle) {
            super(basePresenter);
            tv_name1 = ((TextView) findViewById(R.id.tv_name1));//.setText(weightChangeInfo.getName());
            tv_weight1 = ((TextView) findViewById(R.id.tv_weight1));//.setText(NumberHelp.formatMoney(weightChangeInfo.getWeight(), 3, "--"));
            tv_price1 = ((TextView) findViewById(R.id.tv_price1));//.setText(SteelardHelp.formatMoney(weightChangeInfo.getUnitPrice()));
            tv_money = ((TextView) findViewById(R.id.tv_money));
            tv_title = ((TextView) findViewById(R.id.tv_title));
            tv_weight_unit = ((TextView) findViewById(R.id.tv_weight_unit));
            tv_price_weight_unit = ((TextView) findViewById(R.id.tv_price_weight_unit));
        }

        @Override
        public boolean isExit() {
            return SaleUIFragment.this.isExit();
        }

        @Override
        public void setPageTitle(String title) {
            ((TextView) findViewById(R.id.tv_title)).setText(title);
        }

        @Override
        public void upWeightChangeInfo(String name, String weight, String unitPrice, String totalPrice) {
            tv_name1.setText(name);
            tv_weight1.setText(weight);
            tv_price1.setText(unitPrice);
            tv_money.setText(totalPrice);
            tv_weight_unit.setText("(" + RunTimeData.getAppWeightUnit() + ")");
            tv_price_weight_unit.setText("(元/" + RunTimeData.getAppWeightUnit() + ")");
            //P.d("Bill-> weight:" + weight);

            double subPrice = Double.parseDouble(weight);
            isSubPriceZero = subPrice <= 0;

            if (subPrice > 0) {
                closeShopScreen();
            }
        }


        @Override
        public void showPaySuccess(SaleContract.PrintInfo printInfo) {
            RouterUINavigation.getInstance().showVipOrderFix((BaseFragmentActivity) getActivity());
//            RouterUINavigation.getInstance().showPaySuccess((BaseFragmentActivity) getActivity(), printInfo.print, printInfo.qrCode);
        }

        @Override
        public void showTips(int tips) {
            if (tips == 1) {
                ViewUIHelp.showTips(getActivity(), "打印");
            }
        }
    }

    private void closeShopScreen() {
        mCurLeftTime = 0;
        //休眠指令
//        PowerManager powerManager = (PowerManager) getActivity().getSystemService(POWER_SERVICE);
//        powerManager.wakeUp(0);


        //重量大于0 退出待机
        boolean isShowShopScreen = RouterUINavigation.getInstance().containsKey(ShopScreenFragment.shopScreenFragment);
        if (isShowShopScreen/*进入待机状态*/) {
            //P.d("Bill->pollingLeftTime2ShopScreen->关闭富屛");
            RouterUINavigation.getInstance().dismiss(ShopScreenFragment.shopScreenFragment);
        }
        if (RunTimeData.go2ScreenOn != 0 && !mIsBright /*&& !mPowerManager.isScreenOn()*/) {
            mIsBright = true;
            //P.d("Bill->亮屏->mIsBright:" + mIsBright);
            //RootCommand.runT("input keyevent " + KeyEvent.KEYCODE_POWER);//亮屏
            RootCommand.runT("echo 255 > /sys/class/backlight/rk28_bl/brightness");//亮屏
        }
    }

    private Disposable mLeftTime2ShopScreenDisposable = null;
    private int        mCurLeftTime;
    private Boolean    mIsBright                      = true;//是否亮屏

    @SuppressLint("CheckResult")
    private void pollingLeftTime2ShopScreen() {
        if (mLeftTime2ShopScreenDisposable != null) mLeftTime2ShopScreenDisposable.dispose();
        Observable.create((ObservableOnSubscribe<String>) e -> {
            boolean isFragmentMapEmpty = RouterUINavigation.getInstance().isFragmentMapEmpty();
            //P.d("Bill->->isSubPriceZero:" + isSubPriceZero + ",mCurLeftTime:" + mCurLeftTime + ",剩余" + mCurLeftTime % RunTimeData.go2Screen + "秒进入商户屏,剩余" + mCurLeftTime % RunTimeData.go2ScreenOn + "秒进入熄屏");
            BasisEntity basisEntity = RunTimeData.steelyardInfo.basisEntity;
            if (isSubPriceZero && mCurLeftTime != 0 && (mCurLeftTime % RunTimeData.go2Screen == 0) /*这里还需要判断尚未打开富屛*/ && isFragmentMapEmpty && basisEntity != null) {
                //TODO:打开富屛
                RouterUINavigation.getInstance().showShopScreen((BaseFragmentActivity) getActivity());
//                if (myService != null) {
//                    P.d("Bill->关闭屏幕：getBrightness:" + myService.getBrightness());
//                    myService.setBrightness(0);
//                }
                //P.d("Bill->pollingLeftTime2ShopScreen->打开富屛");
            }
            boolean isShowShopScreen = RouterUINavigation.getInstance().containsKey(ShopScreenFragment.shopScreenFragment);
            if (RunTimeData.go2ScreenOn != 0 && isSubPriceZero && mCurLeftTime != 0 && (mCurLeftTime % RunTimeData.go2ScreenOn == 0) && (isFragmentMapEmpty || isShowShopScreen)) {
                if (mIsBright) {
                    mIsBright = false;
                    //P.d("Bill->熄屏->isScreenOn:" + mIsBright);
                    //RootCommand.runT("input keyevent " + KeyEvent.KEYCODE_POWER);//熄屏
                    RootCommand.runT("echo 0 > /sys/class/backlight/rk28_bl/brightness");//熄屏
                }
            }
            mCurLeftTime++;
            e.onComplete();
        })
                .repeatWhen(it -> it.flatMap((Function<Object, ObservableSource<?>>) o -> Observable.timer(1, TimeUnit.SECONDS)))
                .compose(upstream -> upstream.subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread(), true))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mLeftTime2ShopScreenDisposable = d;
                    }

                    @Override
                    public void onNext(String s) {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }


    private class SubtotalView implements SaleContract.SubtotalView {


        protected SaleContract.SubtotalPresenter basePresenter;


        private ListView                     listView;
        private MAdapter                     adapter;
        private List<OrderEntity.GoodEntity> souceList = new ArrayList<>();//购物车商品数据

        private TextView tv_tprice1, tv_weight_unit_title;

        private View v_editsubtotal;


        public SubtotalView(SaleContract.SubtotalPresenter basePresenter) {

            this.basePresenter = basePresenter;
            basePresenter.binView(this);

            listView = findViewById(R.id.vg_list).findViewById(android.R.id.list);
            listView.setAdapter(adapter = new MAdapter());

            tv_weight_unit_title = ((TextView) findViewById(R.id.tv_weight_unit_title));
            tv_weight_unit_title.setText("重量(" + RunTimeData.getAppWeightUnit() + ")");

            tv_tprice1 = ((TextView) findViewById(R.id.tv_tprice1));

            v_editsubtotal = findViewById(R.id.v_editsubtotal);
        }

        @Override
        public SaleContract.SubtotalPresenter getPresenter() {
            return basePresenter;
        }


        @Override
        public void setPresenter(SaleContract.SubtotalPresenter presenter) {
            basePresenter = presenter;
        }

        @Override
        public void upSubtotal(List<OrderEntity.GoodEntity> sourceList_) {
            this.souceList = sourceList_;
            //P.d("Bill->sourceList_:" + sourceList_.size());
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    adapter.notifyDataSetChanged();
                    listView.setSelection(souceList.size());
                }
            });
        }


        @Override
        public void editSubtotal(boolean isEditSubtotal_) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    isEditSubtotal = isEditSubtotal_;
                    v_editsubtotal.setVisibility(isEditSubtotal ? View.VISIBLE : View.GONE);
                    LockKeyManager.curPageLockChange();
//                    AppConst.getModuleManager().loadModule(FunModule.class).setLockKeySwitch(isEditSubtotal);
                }
            });

        }


        @Override
        public void upSubtotalTotalPrice(String allTotalPrice) {
            tv_tprice1.setText(allTotalPrice);
        }

        @Override
        public void showTips(int tips) {
            if (tips == 3)
                AppUIHelp.tryShowTipsSHORT("无商品，重量或是价格不可为0");

        }

        @Override
        public void confirmClearList(Runnable confirmRun) {
            if (!isExit())
                new HandleDialog().show(getActivity(), "是否清除累计？\n如需结账，请按“支付打印”结算订单", OnSteelyardKeyEvent.KEYCODE_9, "清除累计（按9）", new Runnable() {
                    @Override
                    public void run() {
                        if (confirmRun != null)
                            confirmRun.run();
                    }
                }, true);

        }

        @Override
        public void showPay() {
            switch (RunTimeData.tmpPayType) {
                //微会员
                case DelegatePayTask.PayType_WVip:
                    //TODO:这里提交订单获取支付信息。
                    PayApi.getVipPayUrl(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            try {
                                GetPayBean getPayBean = JzUtil.mGson.fromJson(response.body(), GetPayBean.class);
                                if (getPayBean != null && getPayBean.res == 0) {
                                    Print.showToast(getPayBean.msg);
                                    return;
                                }
                                if (null != getPayBean && null != getPayBean.data && null != getPayBean.data.content && !getPayBean.data.content.isEmpty()) {
                                    //成功
                                    RouterUINavigation.getInstance().showPay01((BaseFragmentActivity) getActivity(), RunTimeData.tmpPayType, getPayBean.data.content, getPayBean.data.ordernum);
                                } else {
                                    Print.showToast("微会员支付失败");
                                }
                            } catch (Exception exception) {
                                Print.showToast("微会员支付失败" + exception);
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            Print.showToast("网络貌似不给力 ~ 请检查你的网络后重试 " + response.getException());
                        }
                    });
                    break;
                //扫码支付  聚合静态码
                case DelegatePayTask.PayType_StaticDelegate:
                    //这里获取本地是否存在静态码支付
                    if (RunTimeData.steelyardExtData.payOutLineInfo.payOutlineItems != null && !RunTimeData.steelyardExtData.payOutLineInfo.payOutlineItems.isEmpty()) {
                        RouterUINavigation.getInstance().showPay01((BaseFragmentActivity) getActivity(), RunTimeData.tmpPayType, null, null);
                    } else {
                        Print.showToast("未上传静态码！");
                    }
                    break;
                default:
                    RouterUINavigation.getInstance().showPay((BaseFragmentActivity) getActivity(), RunTimeData.tmpPayType);
                    break;
            }
        }

        private class MAdapter extends BaseHoldAdapter {
            public MAdapter() {
                super(holdCycleHelp());
            }

            @Override
            public void notifyDataSetChanged() {
                super.notifyDataSetChanged();

            }

            @Override
            public IHoldView createHoldView(int position, View convertView, ViewGroup parent) {
                return new MHoldView();
            }

            @Override
            public int getCount() {
                return CollectionHelp.getSize(souceList);
            }

            @Override
            public Object getItem(int position) {
                return souceList.get(position);
            }
        }

        private class MHoldView extends LinearLayout implements IHoldView<OrderEntity.GoodEntity> {

            private TextView tv_name, tv_price_unit, tv_weight, tv_totalPrice, tv_no;

            public MHoldView() {
                super(getActivity());
                ViewHelp.inflate(getActivity(), R.layout.item_sales, this);
                tv_no = (TextView) this.findViewById(R.id.tv_no);
                tv_name = (TextView) this.findViewById(R.id.tv_name);
                tv_price_unit = (TextView) this.findViewById(R.id.tv_price_unit);
                tv_weight = (TextView) this.findViewById(R.id.tv_weight);
                tv_totalPrice = (TextView) this.findViewById(R.id.tv_totalPrice);

            }

            private int position;

            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public Object binData(OrderEntity.GoodEntity obj, int position, boolean isonPause) {
                this.position = position;


                setBackgroundColor(position % 2 == 1 ? Color.YELLOW : Color.TRANSPARENT);
                tv_no.setText("" + (position + 1));
                tv_name.setText(obj.goodName);
                tv_price_unit.setText(SteelardHelp.formatMoney(obj.unitPrice));
                if (obj.unitType == 2) {

                    tv_weight.setText(((int) obj.weight) + "件");
                } else {
                    tv_weight.setText(NumberHelp.formatMoney(obj.weight, 3, "--"));
                }
                tv_totalPrice.setText(SteelardHelp.formatMoney(obj.calPrice()));

                setTag(obj);
                return null;
            }

        }


    }


    private class GoodImageView implements SaleContract.GoodImageView {

        private TextView          tv_img_tips;
        private ImageView         img_good;
        private ImageViewLoadHelp payImageViewLoadHelp;

        protected SaleContract.GoodImagePresenter basePresenter;

        public GoodImageView(SaleContract.GoodImagePresenter basePresenter) {
            this.basePresenter = basePresenter;
            basePresenter.binView(this);

            tv_img_tips = ((TextView) findViewById(R.id.tv_img_tips));
            img_good = findViewById(R.id.img_good);
            payImageViewLoadHelp = new ImageViewLoadHelp(getActivity(), Math.max(getResources().getDisplayMetrics().heightPixels, getResources().getDisplayMetrics().widthPixels), holdCycleHelp());
            payImageViewLoadHelp.setHasImagScaleType(ImageView.ScaleType.CENTER_INSIDE);
            payImageViewLoadHelp.setLoadingImagScaleType(ImageView.ScaleType.CENTER_INSIDE);
            payImageViewLoadHelp.setNotImagScaleType(ImageView.ScaleType.CENTER_INSIDE);
        }

        @Override
        public SaleContract.GoodImagePresenter getPresenter() {
            return basePresenter;
        }

        @Override
        public void setPresenter(SaleContract.GoodImagePresenter presenter) {
            basePresenter = presenter;
        }


        @Override
        public void showTackGoodImage(String imgPath) {

            if (isExit()) return;
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    payImageViewLoadHelp.setImage(img_good, imgPath);
                    AlphaAnimation animation = new AlphaAnimation(1, 0);
                    animation.setFillAfter(true);
                    animation.setDuration(500);
                    animation.setStartOffset(1000);

                    ((View) img_good.getParent()).startAnimation(animation);
                }
            });


        }

        @Override
        public void showTackGoodImageByAi(String imgPath) {
            showTackGoodImage(imgPath);
            ViewUIHelp.showTipsView(getActivity(), "正在设别菜品...");
        }

        @Override
        public void showGoodImageDiscern(String goodName) {
            if (StringHelp.isEmpty(goodName)) {
                tv_img_tips.setVisibility(View.INVISIBLE);
                tv_img_tips.setText("");
            } else {
                tv_img_tips.setText(goodName);
                tv_img_tips.setVisibility(View.VISIBLE);
            }
        }

    }


}
